package com.jsfcompref.solutech.backing;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;

import org.apache.myfaces.custom.fileupload.UploadedFile;

import com.eCommerce.corecontract.criteria.CategorieCriteria;
import com.eCommerce.corecontract.dto.CategorieDTO;
import com.eCommerce.corecontract.dto.ComposantDTO;
import com.eCommerce.corecontract.exception.EcommerceException;
import com.eCommerce.server.corebackend.util.BackEndConstants;
import com.eCommercecorecontract.svco.ICategorieSVCO;
import com.eCommercecorecontract.svco.IComposantSVCO;
import com.eCommercecorecontract.svco.SVCOFinder;
import com.ecommerceWeb.common.FileUtil;
import com.ecommerceWeb.common.MessageFactory;
import com.ecommerceWeb.common.ServiceFinder;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CreerComposant
{
	
	  private HtmlInputText  libelle;
	  private HtmlInputTextarea description;
	  private HtmlSelectOneMenu categorieLibelle;
	  private List<SelectItem> categorieLibelleItems;
	  private HtmlSelectOneMenu quantiteStock;
	  private List<SelectItem> quantites;
	  private UploadedFile upFile;
	  private HtmlInputText  prix;
	  private String filename;
	  private boolean exist;
	  private String message=null;

//modif
	public CreerComposant()
	{
	}
	
	public void validatePrix(FacesContext context, UIComponent toValidate,
			Object value) throws ValidatorException {
		boolean isValid = false;
		String expression = "[0-9]*\\.?[0-9]+$"; 
		Pattern pattern = Pattern.compile(expression);
		Matcher matcher = pattern.matcher((String) value);
		if(matcher.matches()){
			isValid = true;  
		}else{
			isValid = false; 
			FacesMessage message = new FacesMessage("Prix incorrect!");
			throw new ValidatorException(message);
		}
	}

 
	public String creerComposant() {
		String status=MessageFactory.status_composant_failure ;
		 try {
			SVCOFinder sVCOFinder = (SVCOFinder) ServiceFinder.findBean("SVCOFinder");
			IComposantSVCO composantSVCO;
			ICategorieSVCO categorieSVCO;
			ComposantDTO composant = new ComposantDTO();
			CategorieDTO categorie = new CategorieDTO();
			
			composantSVCO = (IComposantSVCO) sVCOFinder.get(BackEndConstants.SVCO_COMPOSANT);
			categorieSVCO = (ICategorieSVCO) sVCOFinder.get(BackEndConstants.SVCO_CATEGORIE);
			
			categorie.setId(Long.parseLong(categorieLibelle.getValue().toString()));
			categorie = categorieSVCO.visualiserCategorie(categorie);
	
			composant.setCategorieDTO(categorie);
			composant.setLibelle(libelle.getValue().toString());
			composant.setDescription(description.getValue().toString());
			composant.setNbComposantStock(Long.parseLong(quantiteStock.getValue().toString()));
			composant.setPrix(Double.parseDouble(prix.getValue().toString()));
			
			
			System.out.println("File type: " + upFile.getContentType());
	        System.out.println("File name: " + upFile.getName());
	        System.out.println("File size: " + upFile.getSize() + " bytes");
	        try {
	            // Precreate an unique file and then write the InputStream of the uploaded file to it.
	            String uploadedFileName = FileUtil.trimFilePath(upFile.getName());
	            
	            ServiceFinder serviceFinder=new ServiceFinder();
	            
	            PropertyResourceBundle bundle=(PropertyResourceBundle) PropertyResourceBundle.getBundle("com.ecommerceWeb.common.FileConfiguration");
	            String chemin = bundle.getString("image.location");
	            String address = bundle.getString("image.address");
	         
	            System.out.println("chemin="+chemin);
	            
	            int index = upFile.getName().lastIndexOf("\\");  
	            if(index != -1)  
	            {
	            	uploadedFileName = address + upFile.getName().substring(index + 1);
	            }else{
	            	uploadedFileName = address + upFile.getName();  
	            }
	            
	            
	            //---------------------------------------
	            composant.setImage(uploadedFileName);//..setImage(chemin);
	            composantSVCO.ajouterComposant(composant);
	            //----------------------------------------
	            
				setExist(true);
				status=MessageFactory.status_composant_created;

				String msg ="Le composant ' "+ composant.getLibelle()+" ' a ete cree avec succes !";
				setMessage(msg);
				init();
				


	        } catch (Exception e) {
				FacesContext context = FacesContext.getCurrentInstance();
				context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Une erreur s'est produite lors de la creation! ", null));
				setExist(false);
				status=MessageFactory.status_composant_failure;
				e.printStackTrace();
			
	        }
		
			
		} catch (Exception e) {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Une erreur s'est produite lors de la creation!", null));
			setExist(false);
			status=MessageFactory.status_composant_failure;
			e.printStackTrace();
		}
		
		return status;
		
	
	}
	
	public void init()
	{
		 libelle.setValue(null);
		 description.setValue(null);
		 categorieLibelle.setValue(null);
		 quantiteStock.setValue(null);
		 prix.setValue(null);
	}

	public HtmlInputText getLibelle() {
		return libelle;
	}

	public void setLibelle(HtmlInputText libelle) {
		this.libelle = libelle;
	}

	public HtmlInputTextarea getDescription() {
		return description;
	}

	public void setDescription(HtmlInputTextarea description) {
		this.description = description;
	}
	
	public HtmlSelectOneMenu getCategorieLibelle() {
		return categorieLibelle;
	}
	public void setCategorieLibelle(HtmlSelectOneMenu categorieLibelle) {
		this.categorieLibelle = categorieLibelle;
	}

	public void setCategorieLibelleItems(List<SelectItem> categorieLibelleItems) {
		this.categorieLibelleItems = categorieLibelleItems;
	}

	public List<SelectItem> getCategorieLibelleItems() {
		if (categorieLibelleItems == null){
			categorieLibelleItems = new ArrayList<SelectItem>();
	        List categoryList = getCategories();
	        Iterator i=categoryList.iterator();
	        while(i.hasNext()){
	        	CategorieDTO cat = (CategorieDTO) i.next();
	        	categorieLibelleItems.add(new SelectItem(cat.getId(), cat.getLibelle())); // value, label, the value to choose and label to appear fo the user
	        }
	        
	    }
	    return categorieLibelleItems;
	}
	
	
	
	public HtmlSelectOneMenu getQuantiteStock() {
		return quantiteStock;
	}

	public void setQuantiteStock(HtmlSelectOneMenu quantiteStock) {
		this.quantiteStock = quantiteStock;
	}

	public List<SelectItem> getQuantites() {
		
		quantites = new ArrayList<SelectItem>();
		for(int i =1;i<31;i++){
			quantites.add(new SelectItem(i));
		}
		return quantites;
	}

	public void setQuantites(List<SelectItem> quantites) {
		this.quantites = quantites;
	}

	public UploadedFile getUpFile() {
		return upFile;
	}

	public void setUpFile(UploadedFile upFile) {
		this.upFile = upFile;
	}

	
	public List getCategories()
	  {		
			List cats = null;
			try {
				SVCOFinder sVCOFinder=(SVCOFinder) ServiceFinder.findBean("SVCOFinder");
				ICategorieSVCO categorieSVCO=(ICategorieSVCO)sVCOFinder.get(BackEndConstants.SVCO_CATEGORIE);
				
				cats = categorieSVCO.listerCategorie();
			} catch (EcommerceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


	  return cats;
	  }

	public void setPrix(HtmlInputText prix) {
		this.prix = prix;
	}

	public HtmlInputText getPrix() {
		return prix;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getFilename() {
		return filename;
	}

	public boolean isExist() {
		return exist;
	}

	public void setExist(boolean exist) {
		this.exist = exist;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	
}